from flask import Blueprint, jsonify, make_response
from flask_restful import Api,Resource,reqparse
from models.user import OAuthUserModel,User
from common.utils.my_output_json import custom_uotput_json
oatuh_weibo_bp = Blueprint('oatuh_weibo_bp',__name__,url_prefix='/oauth')
from flask import current_app
api = Api(oatuh_weibo_bp)
import time,hmac,base64,urllib,requests,json
from common.jwt_token import gen_toen
from urllib.parse import parse_qs,urlencode
@api.representation('application/json')
def output_json(data, code, headers=None):
    resp = custom_uotput_json(data, code)
    return resp

class WeiBoResource(Resource):
    def get(self):
        """根据code，获取微博用户信息"""
        parser = reqparse.RequestParser()
        parser.add_argument('code')
        args = parser.parse_args()
        # 1 . 获取code值
        code = args.get('code')
        print("code",code)
        #构造获取weibo的用户信息
        client_id = current_app.config.get('CLIENT_ID')
        print(client_id)
        client_secret = current_app.config.get('CLIENT_SECRET')
        print(client_secret)
        base_url = 'https://api.weibo.com/oauth2/access_token'
        data_ = {
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":'authorization_code',
            'code':code,
            'redirect_uri':'http://127.0.0.1:8080/weibo'

        }
        resp = requests.post(url=base_url,data=data_)
        print("resp====>",resp.json())
        #获取用户的唯一标识
        access_token = resp.json()['access_token']
        if not access_token:
            return {'message':'获取用户数据失败','code':500}
        oauth_user = OAuthUserModel.query.filter_by(oauth_id=access_token, oauth_type='weibo').first()
        # True 说明绑定过
        if oauth_user:
            # 获取绑定的用户信息
            user = User.query.filter_by(uid=oauth_user.user).first()
            print(".....", user)
            data = {
                'uid': user.uid,
                'account': user.account
            }
            token = gen_toen(data)
            return {'code': 200, 'account': user.account, 'uid': user.uid, 'token': token}
        else:
            # Flase 说明没绑定用户  去绑定用户
            return {'message': '请绑定用户', 'uid': access_token}
api.add_resource(WeiBoResource,'/weibo')

from werkzeug.security import check_password_hash
from models import db
class DingdingBindUser(Resource):
    """
    1.获取用户信息：用户名，密码，uid
    2.判断用户是否存在数据库里
        1.存在
            校验密码
            直接绑定
        2.不存在
            先去注册
    """
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('account')
        parser.add_argument('password')
        parser.add_argument('unid')
        args = parser.parse_args()
        account = args.get('account')
        pwd = args.get('password')
        unid = args.get('unid')
        #判断用户是否在数据库存在
        user = User.query.filter_by(account=account).first()

        if not user:
            #用户不存在
            return {'message':'用户未注册请先注册','code':400}
        else:
            rest = check_password_hash(user.password,pwd)
            if not rest:
                #密码错误
                return {'message':'密码错误','code':400}
            else:
                #绑定用户
                user_ = OAuthUserModel(oauth_id=unid,user=user.uid,oauth_type='weibo')
                db.session.add(user_)
                db.session.commit()
                data = {
                    'uid':user.uid,
                    'account':user.account
                }
                token = gen_toen(data)
                data_ = {
                    'account':user.account,
                    'token':token,
                    'uid':user.uid
                }
                return {'message':'绑定成功','code':200,'data':data_}

api.add_resource(DingdingBindUser,'/weibo/bind')